const Router = require('koa-router')
const ordered = new Router()
const query = require('../util/db')

// 下订单接口
//http://127.0.0.1:8080/order/add
ordered.post('/add',async ctx => {
    let orderInfo = ctx.request.body
    let sql = `insert into ordered set ?`
    let result = await query(sql,[orderInfo])
    if(result.affectedRows === 1){
        ctx.body = {
            code: 200,
            msg: '订单确认成功'
        }
    }else{
        ctx.bodu = {
            code: 201,
            msg: '订单确认失败'
        }
    }
})

// 根据用户id查询订单
//http://127.0.0.1:8080/order/get?userId=1001
ordered.get('/get',async ctx => {
    let userId = ctx.query.userId
    let sql = `select * from ordered where userid = ?`
    let result = await query(sql,[userId])
    if(result.length >= 1){
        for(let item of result){
            item.goodsList = JSON.parse(item.goodsList)
        }
        ctx.body = {
            code: 200,
            msg: '获取订单信息成功',
            data: result
        }
    }else{
        ctx.body = {
            code: 201,
            msg: '用户还未有订单数据',
            data: []
        }
    }
})

// 删除对应的订单
ordered.delete('/del',async ctx => {
    let {orid} = ctx.request.body
    let sql = `delete from ordered where orid = ?`
    let result = await query(sql,[orid])
    if(result.affectedRows === 1){
        ctx.body = {
            code: 200,
            msg: '删除订单成功'
        }
    }else{
        ctx.body = {
            code: 201,
            msg: '删除订单失败'
        }
    }
})

module.exports = ordered